package com.dianrui.moonfire.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.dialog.UpdateAppDialog;
import com.dianrui.moonfire.interfaces.OnAskDialogCallBack;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.update.DownloadProssDialog;
import com.dianrui.moonfire.update.DownloadService;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;

/**
 * Description:关于
 * User: lzy
 * Date: 2020-8-17
 */
public class AboutActivity extends BaseActivity {
    private int progress;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.ver)
    TextView ver;


    @Override
    public int getContentViewId() {
        return R.layout.activity_about;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initView() {
        title.setText(getString(R.string.about));
        customInit(true);
        ver.setText(MyUtil.getAppVersionName(AboutActivity.this));
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.back, R.id.click_update, R.id.click_info, R.id.txt1, R.id.txt2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.click_info:
                startActivity(new Intent(AboutActivity.this, WebViewActivity.class).putExtra("type", "info"));
                break;
            case R.id.txt1:
                startActivity(new Intent(AboutActivity.this, WebViewActivity.class).putExtra("type", "software"));
                break;

            case R.id.txt2:
                startActivity(new Intent(AboutActivity.this, WebViewActivity.class).putExtra("type", "secret"));
                break;
            //更新
            case R.id.click_update:
                showLoadingDialog(getString(R.string.check_update));
                UpdateApp();
            default:
                break;

        }
    }


    private void UpdateApp() {
        XHttpRequest.getInstance().getRequest(Url.BASE_URL + "/api.php/Apply/update/version_code/" + MyUtil.getVersionName() + "/apply_type/1", new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) throws JSONException {
                if (!StringUtils.isEmpty(result)) {
                    JSONObject jsonObject = new JSONObject(result);
                    if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                        dismissLoadingDialog();
                        String explain=jsonObject.optJSONObject("data").optString("explain");
                        String title=jsonObject.optJSONObject("data").optString("title");
                        final String store_url=jsonObject.optJSONObject("data").optString("store_url");
                        final String isUpdate=jsonObject.optJSONObject("data").optString("is_update");
                        UpdateAppDialog.createStartCarDialog(AboutActivity.this, title, explain, isUpdate,new OnAskDialogCallBack() {
                            @Override
                            public void onokey(Dialog dialog) {
                                dialog.dismiss();
                                update(store_url);
                            }

                            @Override
                            public void onCancel(Dialog dialog) {
                                dialog.dismiss();

                            }
                        });
                    }else {
                        dismissLoadingDialog();
                        ToastUtil.showToast(jsonObject.optString("message"));
                    }
                }
            }

            @Override
            public void failedRequest(String result) {   dismissLoadingDialog();}
        });
    }


    private DownloadProssDialog downloadProssDialog;
    DownloadService downloadService;
    DownloadService.LocalBinder localBinder;
    private int isException = 0;

    private void update(String apkPath) {
        LogUtils.e("apkpath==" + apkPath);
        if (null == downloadProssDialog) {
            downloadProssDialog = new DownloadProssDialog(this, R.style.RcDialog);
        }
        downloadProssDialog.show();
        downloadProssDialog.setProgress(0, "连接服务器中,请等待...");
        Intent intent = new Intent(this, DownloadService.class);
        intent.setAction(DownloadService.ACTION_UPDATE);
        intent.putExtra(DownloadService.EXTRA_APK_PATH, apkPath);
        startService(intent);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }


    private final ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder binder) {
            downloadService = ((DownloadService.LocalBinder) binder).getService();
            localBinder = (DownloadService.LocalBinder) binder;
            listenProgress();
        }

        public void onServiceDisconnected(ComponentName arg0) {
            downloadService = null;
        }
    };

    boolean flag = true;

    void listenProgress() {
        Observable.interval(100, TimeUnit.MILLISECONDS)
                .takeWhile(new Func1<Long, Boolean>() {
                    @Override
                    public Boolean call(Long aLong) {
                        return localBinder.getProgress() <= 100 && flag;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {
                        LogUtils.e("onCompleted");
                        LogUtils.e(localBinder.getDownloadExceptionInfo());
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("onError==" + e.toString());
                    }

                    @Override
                    public void onNext(final Object aLong) {
                        progress = localBinder.getProgress();
                        LogUtils.e("当前app下载进度:" + progress);
                        if (progress < 100 && progress >= 0) {
                            if (null != downloadProssDialog) {
                                //pd.setMessage("正在下载中 : " + progress + "%");
                                downloadProssDialog.show();
                                downloadProssDialog.setProgress(progress, "正在下载中...");
                            }
                        } else if (progress >= 100) {
                            flag = false;
                            LogUtils.e("下载完成" + flag);
                            dismissDialog();
                        }else if (progress == -100) {
                            dismissDialog();
                            if (isException == 0) {
                                isException++;
                                Log.e("localBinder异常",localBinder.getDownloadExceptionInfo());
                                ToastUtil.showToast(localBinder.getDownloadExceptionInfo());
                            }
                        }


                    }
                });
    }

    private void dismissDialog() {
        if (null != downloadProssDialog) {
            downloadProssDialog.dismiss();
            localBinder.setDownloadEnd();
            downloadProssDialog = null;
        }
        unbindService(mConnection);
    }

}
